package com.github.niefy.modules.wx.config;

import me.chanjar.weixin.mp.config.impl.WxMpDefaultConfigImpl;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.ObjectUtils;

import java.util.concurrent.TimeUnit;

/**
 * @author welisit
 * @create 2020-10-09 16:59
 */
public class WxMpLettuceRedisConfigImpl extends WxMpDefaultConfigImpl {

    private StringRedisTemplate stringRedisTemplate;

    private static final String ACCESS_TOKEN_KEY = "wp:access_token:";

    private String accessTokenKey;

    public WxMpLettuceRedisConfigImpl(StringRedisTemplate stringRedisTemplate){
        this.stringRedisTemplate = stringRedisTemplate;
    }

    /**
     * 每个公众号生成独有的存储key.
     */
    @Override
    public void setAppId(String appId) {
        super.setAppId(appId);
        this.accessTokenKey = ACCESS_TOKEN_KEY.concat(appId);
    }

    @Override
    public String getAccessToken() {
        return stringRedisTemplate.opsForValue().get(accessTokenKey);
    }

    @Override
    public boolean isAccessTokenExpired() {
        Long expireTime = stringRedisTemplate.getExpire(accessTokenKey);
        if (ObjectUtils.isEmpty(expireTime)) {
            return true;
        }
        // 到期时间小于2秒就算作过期了，就重新调用接口获取
        return expireTime < 2;
    }

    @Override
    public synchronized void updateAccessToken(String accessToken, int expiresInSeconds) {
        stringRedisTemplate.opsForValue().set(accessTokenKey, accessToken, expiresInSeconds - 200, TimeUnit.SECONDS);
    }

    @Override
    public void expireAccessToken() {
        stringRedisTemplate.expire(accessTokenKey, 0, TimeUnit.SECONDS);
    }


    @Override
    public long getExpiresTime() {
        Long expire = stringRedisTemplate.getExpire(accessTokenKey);
        return expire == null ? 0 : expire;
    }

    @Override
    public void setExpiresTime(long expiresTime) {
        stringRedisTemplate.expire(accessTokenKey, expiresTime, TimeUnit.SECONDS);
    }
}